package gw.com.android.ui.trade.Fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.gts2.hx.R;

import org.json.JSONException;

import java.util.ArrayList;

import butterknife.BindView;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.terminal.GTSDataListener;
import gw.com.android.ui.dialog.PopupConfirmDialog;
import gw.com.android.ui.trade.TradeBusiness;
import gw.com.android.ui.trade.TradeOrderActivity;
import gw.com.android.ui.trade.TradeRangeModel;
import gw.com.android.ui.views.NumericEdit;
import gw.com.android.ui.views.TitleRangeView;
import gw.com.android.utils.ColorThemeUtil;
import gw.com.jni.library.terminal.GTSConst;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import www.com.library.app.Logger;
import www.com.library.model.DataItemDetail;
import www.com.library.util.DoubleConverter;
import www.com.library.util.StringFormatter;
import www.com.library.view.NumberInput;

/**
 * 市价平仓请求界面
 * 
 * @author Reeta.zou
 * 
 */
public class MarketOrderCloseFragment extends BaseOrderFragment {

	@BindView(R.id.morder_title_deviation)
	TitleRangeView mRangeTitleView;
	@BindView(R.id.morder_title_lot)
	TitleRangeView mLotTitleView;
	/** 产品名称 */
	@BindView(R.id.proNameView)
	TextView mPrdNameView;
	/** 手数加减器 */
	@BindView(R.id.morder_input_lot)
	NumericEdit m_lotEditView;
	/** 最大偏移加减器 */
	@BindView(R.id.morder_input_deviation)
	NumericEdit m_deviationEditView;
	/** 开仓时间 */
	@BindView(R.id.open_time)
	TextView m_opentime;
	@BindView(R.id.open_price)
	TextView m_openprice;
	@BindView(R.id.profit_loss)
	TextView m_profitloss;

	/** 订单id */
	private int mOrderID = 0;
	/** 偏移量默认值 */
	private String mCurRange = "0";


	/**
	 * 更新通知处理
	 */
	public final Handler HandlerCallback = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case GTSConst.REPLY_SYMBOL_TICK_UPDATE:
				// 更新界面价格
				updateWithPrice();
				break;
			case GTSConst.REPLY_POSTION_UPDATELIST:
				// 更新盈亏
				updateProfit();
				break;
			case GTSConst.REPLY_SYMBOL_UPDATE:
				onConfigDynamicViews();
				checkError();
				break;
			}
		}
	};

	@Override
	public void setArguments(Bundle args) {
		super.setArguments(args);
		if (args != null) {
			mOrderID = args.getInt("id");
			mUiCode = args.getInt("uiCode");
			mPositionModel = DataManager.instance().getPositionModel(mOrderID);
			mTickModel = DataManager.instance().getTickModel(mUiCode);
			updateSymbolModel();
			if (null == mPositionModel || 0 == mUiCode || null == mSymbolModel) {
				Logger.e("平仓mPositionModel对象为空，出现异常"+ mUiCode);
				if (null != getActivity()) {
					// 此处获取activity必定为空
					getActivity().finish();
				}
				return;
			}

			mSymbol = DataManager.instance().getPrdName(mPositionModel);
			if (mPositionModel.getInt(GTSConst.JSON_KEY_DIRECTION) == AppContances.TRADE_TYPE_BUY) {
				mTradeDir = AppContances.TRADE_TYPE_SALE;
			} else {
				mTradeDir = AppContances.TRADE_TYPE_BUY;
			}
			mCurRange = GTConfig.instance().getProductRange(mUiCode, mSymbolModel.getInt(GTSConst.JSON_KEY_RANGE)+"");
		}
	}

	@Override
	protected int getLayoutId() {
		return R.layout.fragment_order_close_market;
	}

	@Override
	protected void initLayoutView() {
		super.initLayoutView();
		if (mTradeDir == AppContances.TRADE_TYPE_BUY) {
			m_buyLayout.setSelected(true);
			m_sellLayout.setSelected(false);
		} else {
			m_buyLayout.setSelected(false);
			m_sellLayout.setSelected(true);
		}

		mRangeTitleView.setTitleView(R.string.order_title_deviation);
		mLotTitleView.setTitleView(R.string.order_title_lot);
		m_deviationEditView.setLongClickable(false);
		m_lotEditView.setLongClickable(false);
		mRootView.findViewById(R.id.morder_container_lot);
		mRootView.findViewById(R.id.morder_container_deviation);
		m_deviationEditView.setAfterTextChangedListener(mTextChangedListener);
		m_lotEditView.setAfterTextChangedListener(mTextChangedListener);
		m_lotEditView.getNumericInput().setOnFocusChangeListener(this);
		m_deviationEditView.getNumericInput().setOnFocusChangeListener(this);
		mRangeModel = new TradeRangeModel();
		cmd = AppContances.ORDER_TYPE_CLOSE;
	}

	@Override
	protected void initViewData() {
		mPrdNameView.setText(mSymbol);
		m_opentime.setText(StringFormatter.instance().secToDateTime(mPositionModel.getInt(GTSConst.JSON_KEY_TIME)));
		m_openprice.setText(mPositionModel.getString(GTSConst.JSON_KEY_OPENPRICE));
		updateProfit();
		updateWithPrice();
		m_deviationEditView.setText(mCurRange);
		m_lotEditView.setText(mPositionModel.getString(GTSConst.JSON_KEY_VOLUME));
		onConfigDynamicViews();
	}

	/**
	 * 刷新盈亏值
	 */
	private void updateProfit(){
		m_openprice.setText(mPositionModel.getString(GTSConst.JSON_KEY_OPENPRICE));
		m_profitloss.setText(mPositionModel.getString(GTSConst.JSON_KEY_PROFIT));
		ColorThemeUtil.instance().setPriceColor(m_profitloss, mPositionModel.getInt(GTSConst.JSON_KEY_PROFITSTATE));
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		if (!hidden) {
			if (null != TradeOrderActivity.mInstance && TradeOrderActivity.mInstance.hasChangeRange) {
				mCurRange = GTConfig.instance().getProductRange(mUiCode, mSymbolModel.getString(GTSConst.JSON_KEY_RANGE) + "");
				if (null != m_deviationEditView) {
					m_deviationEditView.setText(mCurRange);
				}
			}
			checkError();
		}
	}

	/**
	 * 输入框文本变化处理
	 */
	private final NumberInput.OnTextChangedListener mTextChangedListener = new NumberInput.OnTextChangedListener() {
		@Override
		public void onTextChanged(EditText edit, Editable s) {
		if (edit == m_lotEditView.getNumericInput()) {
			mCurLot = m_lotEditView.getValueString();
		}
		checkError();
		}
	};

	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		if (v == m_deviationEditView.getNumericInput()) {
			m_deviationEditView.getNumericInput().setText(
					m_deviationEditView.getNumericInput().getValueString());
		}

		checkError();
	}

	/**
	 * 检查界面错误
	 * 
	 * @return
	 */
	private boolean checkError() {
		String errorMessage = "";

		//偏移量
		String rangePrice = m_deviationEditView.getText();
		String errorMessage1 = TradeBusiness.getRangeErrorMsg(mSymbolModel.getString(GTSConst.JSON_KEY_RANGE), rangePrice);
		if (!"".equals(errorMessage1)) {
			mRangeTitleView.setErrorColor();
			errorMessage = errorMessage1;
		}else{
			mRangeTitleView.setDefalutColor();
		}

		//手数
		String lot = m_lotEditView.getText();
		String errorMessage2 = TradeBusiness.getLotErrorMsg(mSymbolModel.getString(GTSConst.JSON_KEY_VOLUMESMIN),
				mPositionModel.getString(GTSConst.JSON_KEY_VOLUME), mSymbolModel.getString(GTSConst.JSON_KEY_VOLUMESSTEP), lot);
		if (!"".equals(errorMessage2)) {
			mLotTitleView.setErrorColor();
			if("".equals(errorMessage)){
				errorMessage = errorMessage2;
			}
		}else{
			mLotTitleView.setDefalutColor();
		}

		if (isVisible() && null != mStatusListener) {
			mStatusListener.onError(errorMessage);
		}

		if(!"".equals(errorMessage)) {
			return true;
		}else {
			return false;
		}
	}

	/**
	 * 设置界面加减器中各属性值
	 * 
	 */
	private void onConfigDynamicViews() {
		// 设置手数
		if (DoubleConverter.toFloatData(mPositionModel.getString(GTSConst.JSON_KEY_VOLUME)) <= DoubleConverter.toFloatData(mSymbolModel.getString(GTSConst.JSON_KEY_VOLUMESMIN))) {
			// 设置最小成交手数小于0.1时，左右的加减都不可以使用
			m_lotEditView.setMax(DoubleConverter.toDoubleData(mPositionModel.getString(GTSConst.JSON_KEY_VOLUME)));
			m_lotEditView.setMin(DoubleConverter.toDoubleData(mPositionModel.getString(GTSConst.JSON_KEY_VOLUME)));
			m_lotEditView.setMinSteps(0);
			m_lotEditView.setDigits(mPositionModel.getString(GTSConst.JSON_KEY_VOLUME));
			mLotTitleView.setRangeView(AppMain.getAppString(R.string.order_hint_lot, mPositionModel.getString(GTSConst.JSON_KEY_VOLUME)), AppMain.getAppString(R.string.order_hint_lot, mPositionModel.getString(GTSConst.JSON_KEY_VOLUME)));
		} else {
			m_lotEditView.setMax(DoubleConverter.toDoubleData(mPositionModel.getString(GTSConst.JSON_KEY_VOLUME)));
			m_lotEditView.setMin(DoubleConverter.toDoubleData(mSymbolModel.getString(GTSConst.JSON_KEY_VOLUMESMIN)));
			m_lotEditView.setMinSteps(DoubleConverter.toDoubleData(mSymbolModel.getString(GTSConst.JSON_KEY_VOLUMESSTEP)));
			m_lotEditView.setDigits(mPositionModel.getString(GTSConst.JSON_KEY_VOLUME).length() + 3, mPositionModel.getString(GTSConst.JSON_KEY_VOLUME).length(), 2);
			mLotTitleView.setRangeView(AppMain.getAppString(R.string.order_hint_lot, mSymbolModel.getString(GTSConst.JSON_KEY_VOLUMESMIN)), AppMain.getAppString(R.string.order_hint_lot, mPositionModel.getString(GTSConst.JSON_KEY_VOLUME)));
		}

		// 设置成交范围
		m_deviationEditView.setMin(0);
		m_deviationEditView.setMax(DoubleConverter.toDoubleData(mSymbolModel.getString(GTSConst.JSON_KEY_RANGE)));
		m_deviationEditView.setMinSteps(1);
		m_deviationEditView.setDigits(mSymbolModel.getString(GTSConst.JSON_KEY_RANGE).length(), mSymbolModel.getString(GTSConst.JSON_KEY_RANGE).length(), 0);
		mRangeTitleView.setRangeView("0", mSymbolModel.getString(GTSConst.JSON_KEY_RANGE)+"");
	}

	/**
	 * 市价平仓前各种条件判断
	 * 
	 * @return
	 */
	@Override
	public boolean hasPostData() {
		if(!"".equals(m_lotEditView.getText())) {
			m_lotEditView.setText(DoubleConverter.toStringData(m_lotEditView.getText(), 2));
		}

		if (checkError()) {
			return false;
		}

		if (!TradeBusiness.PreOrderCheck(getActivity(), mPositionModel.getInt(GTSConst.JSON_KEY_ZONE), mPositionModel.getInt(GTSConst.JSON_KEY_TRADESTATE), false)) {
			return false;
		}

		try {
			jsonData.put(GTSConst.JSON_KEY_ID, mPositionModel.getInt(GTSConst.JSON_KEY_ID));
			jsonData.put(GTSConst.JSON_KEY_CODEID,mPositionModel.getInt(GTSConst.JSON_KEY_CODEID));
			jsonData.put(GTSConst.JSON_KEY_DIRECTION, mTradeDir);
			jsonData.put(GTSConst.JSON_KEY_EXPIRETYPE, AppContances.VALID_TYPE_DAY);
			if (mTradeDir == AppContances.TRADE_TYPE_BUY){
				jsonData.put(GTSConst.JSON_KEY_ORDERPRICE, mPositionModel.getString(GTSConst.JSON_KEY_BUYPRICE));
			}else{
				jsonData.put(GTSConst.JSON_KEY_ORDERPRICE, mPositionModel.getString(GTSConst.JSON_KEY_SELLPRICE));
			}
			mSeq = GTSDataListener.curSeq++;
			GTSDataListener.instance().addSeqList(mSeq+"", cmd+"");
			Logger.e("平仓下单的seq == " + mSeq);
			jsonData.put(GTSConst.JSON_KEY_VOLUME, DoubleConverter.toStringData(m_lotEditView.getText(), 2));
			jsonData.put(GTSConst.JSON_KEY_RANGE, m_deviationEditView.getText());
			jsonData.put(GTSConst.JSON_KEY_ORDERTYPE, AppContances.ORDER_TYPE_CLOSE_TYPE);
			jsonData.put(GTSConst.JSON_KEY_TRADE_SEQ, mSeq);
		}catch (JSONException e){
			e.printStackTrace();
		}

		mDetail.setStringValue("mCurrentTag", AppContances.TAB_ID_CLOSE_ORDER);
		mDetail.setIntValue("mPrdCode", mUiCode);
//		mDetail.setIntValue("mPositionID", mOrderID);
		mDetail.setStringValue("mSymbol", mSymbol);
		mDetail.setIntValue("mTradeDir", mTradeDir);
		mDetail.setStringValue("mCurLot", jsonData.optString(GTSConst.JSON_KEY_VOLUME));

		return true;
	}

	@Override
	public void requstData() {
		int result = AppTerminal.instance().reqOrder(cmd, jsonData.toString());
		if(result != 0){
			if(null != mStatusListener){
				mStatusListener.onFail();
			}
			if(result == 97){
				PopupConfirmDialog.NotifyPrompt(getActivity(), ConfigUtil.instance().mErrorConfigObject.optString(ConfigType.SERVER_ERROR_1016));
			}else{
				PopupConfirmDialog.NotifyPrompt(getActivity(), ConfigUtil.instance().mErrorConfigObject.optString(ConfigType.SERVER_ERROR_1068));
			}
		}
	}

	@Override
	public void registerRxBus() {
		Disposable positionUpdateListRegister = RxBus.getInstance().register(GTSConst.REPLY_POSTION_UPDATELIST+"", Bundle.class).observeOn(AndroidSchedulers.mainThread())
				.subscribe(new Consumer<Bundle>(){

					@Override
					public void accept(@NonNull Bundle bundle) throws Exception {
						if(null != bundle && null != bundle.getIntegerArrayList("object")){
							ArrayList<Integer> codeId = bundle.getIntegerArrayList("object");
							for (int j = 0; j < codeId.size(); j++){
								if(mUiCode == codeId.get(j)){
									DataItemDetail model = DataManager.instance().getPositionModel(mOrderID);
									if(null != model){
										mPositionModel = model;
										HandlerCallback.sendEmptyMessage(GTSConst.REPLY_POSTION_UPDATELIST);
									}
									break;
								}
							}
						}
					}
				});
		bindSubscription(positionUpdateListRegister);

	}

	@Override
	public void onSymbolNotify(DataItemDetail tickModel) {
		if(null != tickModel && mUiCode == tickModel.getInt(GTSConst.JSON_KEY_CODEID)){
			mTickModel = tickModel;
			HandlerCallback.sendEmptyMessage(GTSConst.REPLY_SYMBOL_TICK_UPDATE);
		}
	}

	@Override
	public void onSymbolNotify() {
		super.onSymbolNotify();
		updateSymbolModel();
		HandlerCallback.sendEmptyMessage(GTSConst.REPLY_SYMBOL_UPDATE);
	}

	@Override
	public void onOrderSuccessNotify(int notifyId, int orderId, DataItemDetail model) {
		Logger.e("平仓成功后  orderId = " + orderId + " notifyId == " + notifyId);
		if (mSeq == notifyId) {
			if (null != model) {
				mDetail.setIntValue("mOrderID", model.getInt(GTSConst.JSON_KEY_ID));
				mDetail.setStringValue("mPrice",model.getString(GTSConst.JSON_KEY_CLOSEPRICE));
				mDetail.setStringValue("mOpenPrice",model.getString(GTSConst.JSON_KEY_OPENPRICE));
				mDetail.setStringValue("mTime", StringFormatter.instance().secToDateTime(model.getInt(GTSConst.JSON_KEY_CLOSETIME_)));
				mDetail.setStringValue("mOpenTime", StringFormatter.instance().secToDateTime(model.getInt(GTSConst.JSON_KEY_OPENTIME_)));
				mDetail.setStringValue("Profit", model.getString(GTSConst.JSON_KEY_PROFIT));
				mDetail.setStringValue("Interest", model.getString(GTSConst.JSON_KEY_INTEREST));
				mDetail.setIntValue("ProfitState", model.getInt(GTSConst.JSON_KEY_PROFITSTATE));
			}
			if (null != mStatusListener) {
				Logger.e("onFragmentDealUpdate mStatusListener 平仓成功后  orderId = "
						+ orderId);
				mStatusListener.onSuc(mDetail);
			}
		}
	}
}